﻿<style>
    .model-form .layui-form-label {
        width: 100px;
    }

    .model-form .layui-input-block {
        margin-left: 130px;
    }
</style>

<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 表格工具栏 -->
            <form class="layui-form toolbar">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">Role Name:</label>
                        <div class="layui-input-inline">
                            <input name="roleName" class="layui-input" placeholder="" />
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">Role Code:</label>
                        <div class="layui-input-inline">
                            <input name="roleCode" class="layui-input" placeholder="" />
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">Memo:</label>
                        <div class="layui-input-inline">
                            <input name="comments" class="layui-input" placeholder="" />
                        </div>
                    </div>
                    <div class="layui-inline">
                        &emsp;
                        <button class="layui-btn icon-btn" lay-filter="roleTbSearch" lay-submit>
                            <i class="layui-icon">&#xe615;</i>Search
                        </button>
                    </div>
                </div>
            </form>
            <!-- 数据表格 -->
            <table id="roleTable" lay-filter="roleTable"></table>
        </div>
    </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="roleTbBar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">Edit</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">Delete</a>
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="auth">Authority assignment</a>
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="roleEditDialog">
    <form id="roleEditForm" lay-filter="roleEditForm" class="layui-form model-form">
        <input name="roleId" type="hidden" />
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">Role Name:</label>
            <div class="layui-input-block">
                <input name="RoleName" placeholder="" class="layui-input"
                       lay-verType="tips" lay-verify="required" required />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">Role Code:</label>
            <div class="layui-input-block">
                <input name="RoleCode" placeholder="" class="layui-input"
                       lay-verType="tips" lay-verify="required" required />
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">Memo:</label>
            <div class="layui-input-block">
                <textarea name="Memo" placeholder="" class="layui-textarea"></textarea>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn" lay-filter="roleEditSubmit" lay-submit>Save</button>
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">Cancel</button>
        </div>
    </form>
</script>

<!-- 分配权限 -->
<script type="text/html" id="roleAuthTemplate">
    <form id="roleAuthForm" lay-filter="roleAuthForm" class="layui-form model-form">
        <input name="Id" type="hidden" />
        <!-- 下拉多选，引用：https://gitee.com/maplemei/xm-select -->
        <div class="layui-form-item">
            <label class="layui-form-label">Auth Assign:</label>
            <div class="layui-input-block">
                <div id="MenuIds"></div>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn" lay-filter="roleAuthSubmit" lay-submit>Save</button>
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">Cancel</button>
        </div>
    </form>
</script>

<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'util', 'setter', 'admin', 'xmSelect'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var util = layui.util;
        let setter = layui.setter;
        var admin = layui.admin;
        var xmSelect = layui.xmSelect;

        var arrMenu = [];
        admin.req(layui.setter.appServer + 'Sys_Module/GetTreeList', JSON.stringify({}), function (res) {
            if (res.code === 0) {
                arrMenu = res.data;
            } else {
                layer.msg(res.msg, { icon: 2 });
            }
        }, 'post');

        /* 渲染表格 */
        var insTb = table.render({
            elem: '#roleTable',
            url: layui.setter.appServer + 'sys_role/getlist',
            method: 'post',
            headers: { 'Authorization': setter.getToken() },
            contentType: 'application/json',
            page: {
                limit: 50,
                limits: [20, 50, 100, 500],
                groups: 10
            },
            toolbar: ['<p>',
                '<button lay-event="add" class="layui-btn layui-btn-sm icon-btn"><i class="layui-icon">&#xe654;</i>Add New</button>&nbsp;',
                '<button lay-event="del" class="layui-btn layui-btn-sm layui-btn-danger icon-btn"><i class="layui-icon">&#xe640;</i>Delete</button>',
                '</p>'].join(''),
            cellMinWidth: 100,
            cols: [[
                { type: 'checkbox' },
                { type: 'numbers' },
                { field: 'RoleName', title: 'Role Name', sort: true },
                { field: 'RoleCode', title: 'Role Code', sort: true },
                { field: 'Memo', title: 'Memo', sort: true },
                {
                    field: 'CreateTime', title: 'Create Time', templet: function (d) {
                        return util.toDateString(d.CreateTime);
                    }, sort: true
                },
                { title: 'Operate', toolbar: '#roleTbBar', align: 'center', minWidth: 300 }
            ]]
        });

        /* 表格搜索 */
        form.on('submit(roleTbSearch)', function (data) {
            insTb.reload({ where: data.field, page: { curr: 1 } });
            return false;
        });

        /* 表格工具条点击事件 */
        table.on('tool(roleTable)', function (obj) {
            if (obj.event === 'edit') { // 修改
                showEditModel(obj.data);
            } else if (obj.event === 'del') { // 删除
                doDel(obj);
            } else if (obj.event === 'auth') {  // 权限管理
                showPermModel(obj.data);
            }
        });

        /* 表格头工具栏点击事件 */
        table.on('toolbar(roleTable)', function (obj) {
            if (obj.event === 'add') { // 添加
                showEditModel();
            } else if (obj.event === 'del') { // 删除
                var checkRows = table.checkStatus('roleTable');
                if (checkRows.data.length === 0) {
                    layer.msg('Please select the data to delete.', { icon: 2 });
                    return;
                }
                var ids = checkRows.data.map(function (d) {
                    return d.Id;
                });
                doDel({ ids: ids });
            }
        });

        /* 显示表单弹窗 */
        function showEditModel(mData) {
            admin.open({
                type: 1,
                title: (mData ? 'Edit' : 'Add') + ' Role',
                content: $('#roleEditDialog').html(),
                success: function (layero, dIndex) {
                    // 回显表单数据
                    form.val('roleEditForm', mData);                    
                    // 表单提交事件
                    form.on('submit(roleEditSubmit)', function (data) {
                        if (mData) {
                            for (x in data.field) {
                                mData[x] = data.field[x];
                            }
                        }
                        else {
                            mData = data.field;
                            mData.Id = 0;
                        }
                        var loadIndex = layer.load(2);
                        admin.req(layui.setter.appServer + 'sys_role/saveform', JSON.stringify(mData), function (res) {
                            layer.close(loadIndex);
                            if (0 === res.code) {
                                layer.msg(res.msg, { icon: 1 });
                                insTb.reload({ page: { curr: 1 } });
                            } else {
                                layer.msg(res.msg, { icon: 2 });
                            }
                        }, 'post');
                        return false;
                    });
                }
            });
        }

        /* 删除 */
        function doDel(obj) {
            layer.confirm('Are you sure you want to delete the selected data ?', {
                skin: 'layui-layer-admin',
                shade: .1
            }, function (i) {
                layer.close(i);
                var loadIndex = layer.load(2);
                admin.req('ok.json', {
                    id: obj.data ? obj.data.roleId : '',
                    ids: obj.ids ? obj.ids.join(',') : ''
                }, function (res) {
                    layer.close(loadIndex);
                    if (200 === res.code) {
                        layer.msg(res.msg, { icon: 1 });
                        insTb.reload({ page: { curr: 1 } });
                    } else {
                        layer.msg(res.msg, { icon: 2 });
                    }
                }, 'get');
            });
        }

        /* 权限管理 */
        function showPermModel(mData) {
            admin.open({
                type: 1,
                title: 'Authority assignment',
                content: $('#roleAuthTemplate').html(),
                area: ['520px', '400px'],
                success: function (layero, dIndex) {
                    if (arrMenu == null && arrMenu.length == 0) {
                        layer.msg('Data exception')
                        return
                    }
                    console.log($('#MenuIds').parent().html())
                    var insXmSel = xmSelect.render({
                        el: '#MenuIds',
                        height: '250px',
                        
                        data: arrMenu,
                        initValue: mData.MenuIds ? mData.MenuIds.split(','):[],
                        prop: {
                            name: 'ModuleName',
                            value: 'Id'
                        },
                        radio: false,
                        clickClose: false,
                        tree: {
                            show: true,
                            indent: 15,
                            strict: false,
                            expandedKeys: true
                        }
                    });
                    
                    // 表单提交事件
                    form.on('submit(roleAuthSubmit)', function (data) {
                        mData.MenuIds = insXmSel.getValue('valueStr');
                        if (!mData.MenuIds) {
                            layer.msg('Please select a menu that is visible to the role')
                            return
                        }
                        
                        console.log(mData)

                        var loadIndex = layer.load(2);
                        admin.req(layui.setter.appServer + 'sys_role/saveform', JSON.stringify(mData), function (res) {
                            layer.close(loadIndex);
                            if (0 === res.code) {
                                layer.msg(res.msg, { icon: 1 });
                                insTb.reload({ page: { curr: 1 } });
                            } else {
                                layer.msg(res.msg, { icon: 2 });
                            }
                        }, 'post');
                        return false;
                    });
                }
            });
        }
    });
</script>
